<?php 
/**
 * authorization 公共函数库
 */

/*function api_json_echo( $status = true , $message = "OK" , $data = NULL , $code = 200 , $url = '' )
{
	header("Content-Type:application/json ; charset=utf-8 ");
	$temp = [
		'status' => ( $status == true ) ? 'success' : 'error',
		'message' => $message,
		'code' => $status ? 200 : $code
	];
	if( !empty( $data ) ) $temp [ 'data' ] = $data;
	if( !empty( $url ) ) $temp [ 'url' ] = $url;

	echo json_encode( $temp , JSON_UNESCAPED_UNICODE );exit;
}*/


/**
 * 用户身份验证key值运算
 */
function user_verify_encodeKey( $appsecret , $userName , $num1 , $num2 )
{
	$numc = ( $num1 < 10 ) ? str_pad($num1,2,"0",STR_PAD_LEFT) : $num1; 
	return substr( md5( $appsecret.md5( $userName ).$numc.$num2 ) , $num1 , $num2 );
}

/**
 * 用户身份验证key值解析
 */
function user_verify_analysis( $key )
{
	$num = substr( $key , -4 );
	$num1 = substr( $num , 0 , 2 );
	$num2 = str_replace( $num1 , '' , $num );
	$str = str_replace( $num , '', $key );
	return [ $num1 , $num2 , $str ];
}

/**
 * 用户身份验证key值验证
 */
function user_verify( $key , $appsecret , $userName )
{
	$keyArr = user_verify_analysis( $key );
	list( $num1 , $num2 , $str ) = $keyArr; 
	$verifyStr = user_verify_encodeKey( $appsecret , $userName , $num1 , $num2 );
	if( $str === $verifyStr ){
		return true;
	}
	return false;
}

/**
 * 生成模块标识码
 */
function create_module_code( $store_id )
{
	$num = mt_rand(12,100);
	$code = md5($store_id.$num.time());
	return $code."@".md5($store_id."20200504");
}

/**
 * 从模块标识码中,获取模块id
 */
function get_module_id_by_code( $code )
{
	$pos = strpos( $code , '@' );
	if( $pos == false ){
		return '';
	}
	$id = substr( $code , $pos+1 );
	return $id;
}